package com.felix.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;


/**
 * 增强型Http辅助类
 * @author zhouli
 *
 */
public class EnhancedHttpUtil { 
	
	private static HttpClient httpClient; 
	private static final String TAG = "HttpUtil";
	
	/**
	 * 获得线程安全的HttpClient对象，能够适应多线程环境
	 * @return
	 */
	public static synchronized HttpClient getHttpClient() {
        if (null == httpClient) {
            HttpParams params = new BasicHttpParams();
            // 设置一些基本参数
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params,
                    "UTF-8");
            HttpProtocolParams.setUseExpectContinue(params, true);
            HttpProtocolParams
                    .setUserAgent(
                            params,
                            "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
                                    + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
            // 超时设置
            /* 从连接池中取连接的超时时间 */
            ConnManagerParams.setTimeout(params, 1000);
            /* 连接超时 */
            HttpConnectionParams.setConnectionTimeout(params, 1000);
            /* 请求超时 */
            HttpConnectionParams.setSoTimeout(params, 4000);
          
            // 设置我们的HttpClient支持HTTP和HTTPS两种模式
            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            schReg.register(new Scheme("https", SSLSocketFactory
                    .getSocketFactory(), 443));

            // 使用线程安全的连接管理来创建HttpClient
            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
                    params, schReg);
            httpClient = new DefaultHttpClient(conMgr, params);
        }
        return httpClient;
    }
	
	/**
	 * 获得Post请求对象
	 * @param uri 请求地址，也可以带参数
	 * @param params 如果为null，则不添加由BasicNameValue封装的参数
	 * @return
	 */
	public static HttpPost getPost(String uri, List<BasicNameValuePair> params) {
		HttpPost post = new HttpPost(uri);
		try {
			if(params != null) {
				post.setEntity(new UrlEncodedFormEntity(params));
			}
		} catch (UnsupportedEncodingException e) { 
			e.printStackTrace();
		}
		return post;		
	}
	
	/**
	 * 用户使用的方法
	 * 功能：从服务器获得字符串
	 * @param post
	 * @return
	 */
	public static String getString(HttpPost post) {
		
		HttpClient httpClient = getHttpClient();
		HttpResponse response;
		try {
			response = httpClient.execute(post);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				post.abort();
				return null;
			} 
			return EntityUtils.toString(response.getEntity());
		} catch (ClientProtocolException e) { 
			e.printStackTrace();
			return null;
		} catch (IOException e) { 
			e.printStackTrace();
			return null;
		} 
	}
	
	/**
	 * 用户使用的方法
	 * 功能：请求服务器，返回字符串
	 * @param post post 请求对象
	 * @param requestLimit 请求失败限制次数
	 * @return
	 */
	public static String getString(HttpPost post, int requestLimit) {
		
		if (requestLimit < 1) {
			return null;
		}
		HttpResponse response;
		int currCount = 0; // 当前请求次数
		String result = null;
		
		while (currCount < requestLimit) {
			
			HttpClient httpClient = getHttpClient();
			currCount++;
			try {
				response = httpClient.execute(post);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					return EntityUtils.toString(response.getEntity());
				} else {
					post.abort();
					result = "响应失败,请求终止.";
				} 
			} catch (ClientProtocolException e) {  
				if (currCount > requestLimit) {
					result = "请求失败."; 
					break;
				} 
				System.out.println("ClientProtocolException");
			} catch (IOException e) {  
				if (e instanceof ConnectTimeoutException) {
					result = "连接超时.";
				} else {
					result = "IO异常.";
				}
				if (currCount > requestLimit) {	
					break;
				}
				System.out.println("IOException");
			} finally {
//				System.out.println("finally"); 
			}
		}
		return result;
	}
	
	/**
	 * 用户使用的方法
	 * 功能：请求服务器，返回字符串
	 * @param uri 字符串形式的请求地址
	 * @param requestLimit 最多允许的请求失败次数
	 * @return
	 */
	public static String getString(String uri, int requestLimit) {   
		
		if (requestLimit < 1) {
			return null;
		}
		HttpResponse response;
		int currCount = 0; // 当前请求次数
		String result = null;
		HttpPost post = getPost(uri, null);
		while (currCount < requestLimit) {
			
			HttpClient httpClient = getHttpClient();
			currCount++;
			try {
				response = httpClient.execute(post);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					return EntityUtils.toString(response.getEntity());
				} else {
					post.abort();
					result = "响应失败,请求终止.";
				} 
			} catch (ClientProtocolException e) {  
				if (currCount > requestLimit) {
					result = "请求失败."; 
					break;
				} 
				System.out.println("ClientProtocolException");
			} catch (IOException e) {  
				//Log.e(TAG, e.getMessage());
				if (e instanceof ConnectTimeoutException) {
					result = "连接超时.";
				} else {
					result = "IO异常.";
				}
				if (currCount > requestLimit) {	
					break;
				}
				//System.out.println("IOException");
			} finally {
//				System.out.println("finally"); 
			}
		}
		return result;
	}
	
	/**
	 * 释放建立http请求占用的资源
	 */
	public static void shutdown() { 
		// 释放建立http请求占用的资源
		httpClient.getConnectionManager().shutdown();
		httpClient = null;
	}
}